package cn.zhp.controller;

import cn.zhp.entity.Result;
import cn.zhp.entity.SysArea;
import cn.zhp.service.SysAreaService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * RestController 返回的是json数据
 */
@RestController
@RequestMapping("manager/area")
public class AreaController {

    @Autowired
    SysAreaService service;

    @RequestMapping("")
    public ModelAndView index() {
        return new ModelAndView("/area/area");
    }

    @RequestMapping("toSelect")
    public ModelAndView toSelect() {
        return new ModelAndView("/area/select");
    }

    @RequestMapping("toUpdatePage")
    public ModelAndView toUpdatePage() {
        return new ModelAndView("/area/save");
    }

    @RequestMapping("awesome")
    public ModelAndView awesome() {
        return new ModelAndView("/modules/font-awesome");
    }

    @RequestMapping(value = "selectPage/{pageNum}/{pageSize}")
    public Result selectPage(@RequestBody Map<String, Object> params, @PathVariable("pageNum") int pageNum, @PathVariable("pageSize") int pageSize) {
        PageInfo<SysArea> pageInfo = service.selectPage(pageNum, pageSize, params);
        return new Result(true, "查询成功", pageInfo);//Result 统一结果响应
    }

    @RequestMapping("selectAll")
    public List<SysArea> selectAll() {
        return service.selectAll();
    }

    @RequestMapping("doUpdate")
    public Result doUpdate(@RequestBody SysArea area) {
        area.setUpdateDate(new Date());
        service.updateByPrimaryKeySelective(area);
        return new Result(true, "更新成功", null);
    }

    /**
     * 文件下载，直接通过响应对象的响应流返回给客户端
     * 监听器监听
     */
    @RequestMapping("download")
    public void download(HttpServletResponse response) throws IOException {
        response.setHeader("Content-Disposition", "attachment;filename=" + new String("区域信息.xlsx".getBytes(), "iso8859-1"));
        service.download(response.getOutputStream());
    }

    /**
     * 文件上传
     * */
    @RequestMapping("upload")
    public Result upload(MultipartFile file) throws IOException {
        service.upload(file.getInputStream());
        return new Result(true, "导入成功", null);
    }


}
